//The MIT License
//
//Copyright (c) 2009 nodchip
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package tv.dyndns.kishibe.server;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.Map.Entry;

import tv.dyndns.kishibe.client.Constant;
import tv.dyndns.kishibe.client.game.GameMode;
import tv.dyndns.kishibe.client.packet.PacketRoomKey;
import tv.dyndns.kishibe.client.packet.PacketServerStatus;
import tv.dyndns.kishibe.client.packet.PacketUserData;

public class GameManager {
	private static final String COUNTER_FILE_NAME = "counter.txt";
	private volatile int numberOfCurrentSession;
	private volatile int numberOfCurrentPlayer;
	private volatile PageView pageView;
	private final Random random = new Random();
	private final Set<Integer> loginUserCodes = new HashSet<Integer>();
	private volatile PacketUserData[] loginUsers = new PacketUserData[0];
	private final List<Game> sessions = new ArrayList<Game>();
	private final Map<PacketRoomKey, Game> matchingSessions = new HashMap<PacketRoomKey, Game>();
	private final Object lockStatus = new Object();
	private volatile List<PacketRoomKey> eventRooms = new ArrayList<PacketRoomKey>();
	private Game gameWhole = null;

	public GameManager() {
		try {
			if (new File(COUNTER_FILE_NAME).isFile()) {
				final Scanner scanner = new Scanner(new File(COUNTER_FILE_NAME));
				// ファイルがある場合はそこから読み込み
				pageView = new PageView();
				pageView.session = scanner.nextInt();
				pageView.play = scanner.nextInt();
				pageView.pageView = scanner.nextInt();
				scanner.close();

				new File(COUNTER_FILE_NAME).delete();

				DatabaseFactory.getInstance().savePageView(pageView);
			} else {
				// ファイルが無い場合はデータベースから読み込み
				pageView = DatabaseFactory.getInstance().loadPageView();

				if (pageView == null) {
					pageView = new PageView();
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		ThreadPool.getInstance().addMinuteTasks(new Runnable() {
			public void run() {
				saveServerStatus();
			}
		});

		ThreadPool.getInstance().addMinuteTasks(new Runnable() {
			public void run() {
				updateLoginUsers();
			}
		});
	}

	public synchronized PacketServerStatus getServerStatus(boolean isFirst, int userCode) {
		final PacketServerStatus status = new PacketServerStatus();

		synchronized (lockStatus) {
			status.numberOfCurrentSessions = numberOfCurrentSession;
			status.numberOfAllSessions = pageView.session;
			status.numberOfCurrentPlayers = numberOfCurrentPlayer;
			status.numberOfAllPlayers = pageView.play;
			status.numberOfProblems = ProblemManager.getInstance().getNumberOfProblem();
			status.topPageCounter = pageView.pageView;
			status.numberOfLoginUsers = Math.max(loginUsers.length, loginUserCodes.size());
			status.numberOfActiveUsers = DatabaseFactory.getInstance().getNumberOfActiveUsers();
			status.numberOfPlayersInWhole = getNumberOfPlayersInWhole();
		}

		if (userCode == 0) {
			do {
				userCode = random.nextInt(100000000);
			} while (DatabaseFactory.getInstance().isUsedUserCode(userCode));
		}
		status.userCode = userCode;

		synchronized (loginUserCodes) {
			loginUserCodes.add(userCode);
		}

		if (isFirst) {
			++pageView.pageView;
		}
		status.serverIgnoreUserCodes = new HashSet<Integer>(DatabaseFactory.getInstance().getServerIgnoreUserCode());

		return status;
	}

	public synchronized void saveServerStatus() {
		ThreadPool.getInstance().execute(new Runnable() {
			public void run() {
				DatabaseFactory.getInstance().savePageView(pageView);
			}
		});
	}

	// セッションを返す
	public synchronized Game getSession(int sessionId) {
		if (sessionId >= sessions.size()) {
			return null;
		}
		return sessions.get(sessionId);
	}

	// マッチング状態にあるセッションを返す
	public synchronized Game getMatchingSession(GameMode gameMode, String roomName, int classLevel, String theme, int genre, int type, boolean publicEvent) {
		final PacketRoomKey roomKey = new PacketRoomKey();
		roomKey.set(gameMode, roomName, genre, type);

		Game result = null;
		if (!matchingSessions.containsKey(roomKey) || matchingSessions.get(roomKey).getTransition() != Constant.TRANSITION_MATCHING) {
			final boolean alone;
			final boolean event;

			if (gameMode == GameMode.vsCom) {
				alone = true;
				event = false;

			} else if (gameMode == GameMode.whole) {
				alone = false;
				event = false;

			} else if (gameMode == GameMode.event) {
				alone = false;
				event = true;

			} else if (gameMode == GameMode.theme) {
				alone = true;
				event = false;

			} else {
				// ここには来ないはず
				alone = false;
				event = false;
			}

			final Game game = new Game(this, sessions.size(), classLevel, event, alone, theme, publicEvent);
			matchingSessions.put(roomKey, game);
			sessions.add(game);
			updateEventRooms();
			result = game;
		}

		if (result == null) {
			result = matchingSessions.get(roomKey);
		}

		if (gameMode == GameMode.whole) {
			gameWhole = result;
		}

		return result;
	}

	// 終了したセッションを消去する
	public synchronized void removeSession(int sessionId) {
		sessions.set(sessionId, null);
	}

	public void reportLogin(int userCode) {
		synchronized (loginUserCodes) {
			loginUserCodes.add(userCode);
		}
	}

	public PacketUserData[] getLoginUsers() {
		synchronized (loginUsers) {
			return loginUsers;
		}
	}

	private void updateLoginUsers() {
		synchronized (loginUserCodes) {
			final List<PacketUserData> list = new ArrayList<PacketUserData>();
			for (int userCode : loginUserCodes) {
				list.add(DatabaseFactory.getInstance().getUserData(userCode));
			}

			synchronized (loginUserCodes) {
				loginUsers = list.toArray(new PacketUserData[0]);
			}

			loginUserCodes.clear();
		}
	}

	public void changeStatics(int numberOfCurrentSessionDelta, int numberOfCurrentPlayerDelta, int pageViewDelta, int sessionDelta, int playDelta) {
		synchronized (lockStatus) {
			numberOfCurrentSession += numberOfCurrentSessionDelta;
			numberOfCurrentPlayer += numberOfCurrentPlayerDelta;
			pageView.pageView += pageViewDelta;
			pageView.session += sessionDelta;
			pageView.play += playDelta;

			if (numberOfCurrentPlayer < 0) {
				numberOfCurrentPlayer = 0;
			}
		}
	}

	public synchronized void notifyMatchingCompleted() {
		updateEventRooms();
	}

	public synchronized List<PacketRoomKey> getEventRooms() {
		return eventRooms;
	}

	private synchronized void updateEventRooms() {
		final List<PacketRoomKey> eventRooms = new ArrayList<PacketRoomKey>();
		for (Entry<PacketRoomKey, Game> entry : matchingSessions.entrySet()) {
			final PacketRoomKey key = entry.getKey();
			final Game game = entry.getValue();
			if (game.isEvent() && game.isPublicEvent() && game.getTransition() == Constant.TRANSITION_MATCHING) {
				eventRooms.add(key);
			}
		}
		this.eventRooms = eventRooms;
	}

	public synchronized int getNumberOfPlayersInWhole() {
		if (gameWhole == null || gameWhole.getTransition() != Constant.TRANSITION_MATCHING) {
			return 0;
		}

		return gameWhole.getNumberOfHumanPlayer();
	}
}
